from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from typing import List
import asyncio
app = FastAPI()
# 配置CORS (允许跨域请求)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应更严格
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

a1,a2 = [] ,[]
ingredients = []
dish = []

@app.get("/")
async def root():
    return {"message": "Hello from your PC server!"}

@app.post("/items/")
async def create_items(items: List[str]):  # 接收字符串列表

    global ingredients
    await asyncio.sleep(1)
    global a1 , a2
    global dish
    ingredients.extend(items)

    if ingredients != []:
        print(ingredients,'\n')
        i = 0
        for i in range(0,len(ingredients),2):
            a1.append(ingredients[i])
            a2.append(int(ingredients[i+1]))

        dish = m(a1,a2)
        a1 , a2 = [] , []
        ingredients = []

    return {"message": dish}

@app.get("/recipe/")
async def get_recipe():
    return {"message": dish}


def m(a1,a2):
    # 数据获取和输出
    from pymysql import Connection

    ingredient = a1  # '牛肉', '鸡肉', '上海青', '苦瓜', '柠檬', '西红柿'
    # 食材编号
    id = []
    # 非零元素个数列表（菜谱）
    nums = []
    # 食材匹配度
    match = []
    # 健康程度
    health = []
    # 输出菜品以及匹配度
    dish = []
    # 输出数量
    n = 5
    # 是否腐烂
    rotten = a2  # 0,0,0,0,0,0
    # ingredient 列表获取
    res1 = ()
    # res2_list 的获取
    res2_list = []
    # 连接数据库\获取食材信息
    conn = Connection(
        host="localhost",
        port=3306,
        user="root",
        password="ahj7789t",
    )
    #print(conn.get_server_info())  # 获取服务器版本信息

    cursor = conn.cursor()

    def get_res1():
        conn.select_db("food_kg")
        cursor.execute("select * from ingredient")
        res1 = cursor.fetchall()
        return res1

    res1 = get_res1()

    # print("res1: ",res1,'\n')
    # print(res1)
    # print(len(res1))
    # 遍历食材列表，查找对应的食材编号
    def get_id():
        i, j = 0, 0
        for j in range(len(ingredient)):
            for i in range(len(res1)):
                if ingredient[j] == res1[i][0]:
                    id.append(res1[i][1])

    get_id()
    print("id: ",id,'\n')
    # print(id)

    # 图中匹配菜品
    def get_res2():
        cursor.execute("select * from dish")
        res2 = cursor.fetchall()

        # 菜谱中非零元素的个数
        # print(res2)
        i, j = 1, 0
        for j in range(len(res2)):
            k = 0
            for i in range(1, 5):
                if res2[j][i] != 0:
                    k += 1
            nums.append(k)

        # print(nums)

        # 统计原料的匹配程度
        i, j, k = 1, 0, 0
        for j in range(len(res2)):
            match.append(0)
            health.append(res2[j][-1])
            for i in range(1, 5):
                for k in range(len(id)):
                    if res2[j][i] == id[k]:
                        match[j] += 1
        # print(health)
        # 计算匹配程度：
        i = 0
        for i in range(len(match)):
            match[i] = 100 * match[i] / nums[i] * 0.7 + health[i] * 0.3
        # print(match)
        # 输出菜品以及匹配度
        res2_list = list(res2)
        return res2_list

    res2_list = get_res2()

    # print("res2_list: ",res2_list,'\n')
    def dish_match(match, res2, n):
        dish = []
        i = 0
        while i < n and i < len(match):
            j = 0
            for j in range(len(match)):
                m0 = max(match)
                k = 0
                while m0 != match[k]:
                    k += 1
                if m0 == match[k]:
                    dish.append([res2[k][0], round(m0, 2), res2[k][1], res2[k][2], res2[k][3], res2[k][4], res2[k][5]])
                    match.pop(k)
                    res2.pop(k)
                    i += 1
                    if i == n:
                        break

        # 菜品需要的食材
        i, j, k, l = 0, 0, 0, 0
        for i in range(len(dish)):
            for j in range(len(dish[i]) - 2):
                if dish[i][j + 2] == 0:
                    dish[i][j + 2] = ''
                else:
                    for k in range(len(res1)):
                        if dish[i][j + 2] == res1[k][1]:
                            dish[i][j + 2] = res1[k][0]
            while l < len(dish[i]) - 2:
                if dish[i][l + 2] == '':
                    dish[i].pop(l + 2)
                    l -= 1
                else:
                    l += 1
            l = 0
        return dish

    dish = dish_match(match, res2_list, n)

    def release():
        res1 = ()
        res2_list = []
        id = []
        match = []
        nums = []
        health = []
        ingredient = []
        rotten = []

    release()
    # 判断食材是否腐烂，并扣除分数。
    i, j, k = 0, 0, 0
    for i in range(len(dish)):
        for j in range(len(dish[i]) - 2):
            for k in range(len(ingredient)):
                if dish[i][j + 2] == ingredient[k] and rotten[k] == 1:
                    dish[i][1] -= 10

    print("菜：", dish, '\n')
    return dish
